/**
 * synchronized修饰代码块
 */
public class ThreadSynchronized3 {
    private static int number;
    static class Counter{
        //循环次数
        private static int MAX_COUNT=1000000;
        //自定义锁对象(属性名可以自定义)
        private Object mylock=new Object();

        //++方法
        public void incr(){
            for (int i = 0; i <MAX_COUNT ; i++) {
                synchronized (mylock){
                    number++;
                }
            }
        }
      //--方法
        public void decr(){
            for (int i = 0; i <MAX_COUNT ; i++) {
                synchronized (mylock){
                    number--;
                }
            }
        }

    }
    public static void main(String[] args) throws InterruptedException {
        Counter counter=new Counter();
        Thread t1=new Thread(()->{
           counter.incr();
        });
        t1.start();
        Thread t2=new Thread(()->{
          counter.decr();
        });
        t2.start();
        //等待线程执行完成
        t1.join();
        t2.join();
        System.out.println("最终的结果:"+number);
    }
}